/*
 * @Descripttion: cookie 自定义语法
 * @Use: Cookie.set(), Cookie.get(), Cookie.del(), Cookie.clearAll()
 * @Author: yeming
 * @Date: 2018-06-05 15:51:42
 */

const Cookie = {
  get (name) {
    let ca = document.cookie.split(';');
    for (let i = 0; i < ca.length; i++) {
      let c = ca[i];
      while (c.charAt(0) === ' ') c = unescape(c.substring(1));
      if (c.indexOf(name) !== -1) return unescape(c.substring(name.length + 1, c.length));
    }
    // 不存在当前 name 则返回 false，判断当前 cookie 是否存在
    return false;
  },
  set (cName, value, expire) {
    let exdate = new Date();
    exdate.setTime(exdate.getTime() + expire);
    document.cookie = cName + "=" + escape(value) + ((expire == null) ? "" : ";expires=" + exdate.toGMTString());
  },
  del (name) {
    let exp = new Date();
    exp.setTime(exp.getTime() - 1);
    let cval = Cookie.get(name);
    if (cval !== null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
  },
  clearAll () { // 清除当前（指定）域名下所有cookie
    let cookies = document.cookie.split(";"); // 以“分号”分割生成数组
    if (cookies.length > 0) {
      for (let i = 0; i < cookies.length; i++) {
        let cookie = cookies[i];
        while (cookie.charAt(0) === ' ') cookie = unescape(cookie.substring(1)); // 对中文进行编码，解码使用 unescape
        let eqPos = cookie.indexOf("="); // 匹配“等号”索引
        let name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie; // 取cookie的键名（key）
        document.cookie = name + "=0;path=/;expires=Thu, 01 Jan 1970 00:00:00 GMT;"; // 找到当前域名下对应cookie重置失效时间
        // document.cookie = name + "=0;path=/;domain=" + document.domain + ";expires=Thu, 01 Jan 1970 00:00:00 GMT;"; // 当前域名，例如 liveadmin.tusuav.com
        // document.cookie = name + "=0;path=/;domain=tusuav.com;expires=Thu, 01 Jan 1970 00:00:00 GMT;"; // 指定域名，例如 .tusuav.com
      }
    }
  }
}

export default Cookie;
